<template>
	<div>

		<el-form :inline="true" :model="queryForm" size="small" ref="queryForm"
			style="margin-top: 20px;font-weight: 1000;" class="demo-form-inline">
			<el-form-item style="margin-left: 20px;" label="角色名称" prop="userName">
				<el-input v-model="queryForm.roleName"></el-input>
			</el-form-item>
			<el-form-item label="权限字符" prop="roleChar">
				<el-input v-model="queryForm.roleChar"></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="userState">
				<el-select v-model="queryForm.roleState" placeholder="请选择">

					<el-option v-for="item in dicRoleStateData" :key="item.dicDataId" :label="item.dicDataLabel"
						:value="item.dicDataVal">
						<span style="float: left">{{ item.dicDataLabel }}</span>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="创建时间">
				<el-date-picker v-model="value1" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>

			<span style="margin-left: 20px;">
				<el-form-item>
					<el-button type="primary" @click="searchTableData()" icon="el-icon-search">搜索</el-button>
					<el-button icon="el-icon-refresh" @click="resetQueryForm()">重置</el-button>
				</el-form-item>
			</span>
		</el-form>
		<el-button type="primary" icon="el-icon-plus" size="mini" @click="addRoleButtonClick()" style="margin-left: 20px;" plain>新增
		</el-button>
		<el-button type="success" icon="el-icon-edit" size="mini" @click="editRoleButtonClick()" plain :disabled="editButtonState">
			修改</el-button>
		<el-button type="danger" icon="el-icon-delete" size="mini" @click="delRoleButtonClick()" plain :disabled="delsButtonState">
			删除</el-button>
		<el-button type="info" icon="el-icon-upload2" size="mini" plain>导入</el-button>
		<el-button type="warning" icon="el-icon-download" size="mini" plain>导出</el-button>


		<el-dialog title="添加角色" :visible.sync="addFormVisible" width="30%" style="font-weight: 400;">
			<!-- :rules="sendingMoneyFormRules" -->
			<el-form :model="addRoleForm" hide-required-asterisk ref="addRoleForm" label-width="135px">

				<el-form-item label="角色名称" label-width="80px">
					<el-input v-model="addRoleForm.roleName" placeholder="请输入角色名称"></el-input>
				</el-form-item>
				<el-form-item label="权限字符" label-width="80px">
					<el-input v-model="addRoleForm.roleChar" placeholder="请输入权限名称"></el-input>
				</el-form-item>
				<el-form-item label="角色顺序" label-width="80px">

					<el-input-number v-model="addRoleForm.showOrder" controls-position="right" :min="0" :max="10">
					</el-input-number>
				</el-form-item>

				<el-form-item label="状态" label-width="80px">
					<el-radio-group v-model="addRoleForm.roleState">
						<el-radio :key="item.dicDataId" :label="item.dicDataVal" v-for="item in dicRoleStateData">
							{{item.dicDataLabel}}
						</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="菜单权限" label-width="80px">
					<div class="el-tree tree-border">
						<el-tree :data="treeData" show-checkbox node-key="id" ref="mytree"
							:default-checked-keys="checkedKeys" highlight-current :props="defaultProps">
						</el-tree>
					</div>
				</el-form-item>


				<el-form-item label="备注" label-width="80px">
					<el-input type="textarea" :autosize="{ minRows: 3, maxRows: 10}" placeholder="请输入内容"
						v-model="addRoleForm.remark">
					</el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelForm()">取 消</el-button>
				<el-button type="primary" @click="addRole()">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog title="修改角色" :visible.sync="editFormVisible" width="30%" style="font-weight: 400;">
			<!-- :rules="sendingMoneyFormRules" -->
			<el-form :model="editRoleForm" hide-required-asterisk ref="editRoleForm" label-width="135px">

				<el-form-item label="角色名称" label-width="80px">
					<el-input v-model="editRoleForm.roleName" placeholder="请输入角色名称"></el-input>
				</el-form-item>
				<el-form-item label="权限字符" label-width="80px">
					<el-input v-model="editRoleForm.roleChar" placeholder="请输入权限名称"></el-input>
				</el-form-item>
				<el-form-item label="角色顺序" label-width="80px">

					<el-input-number v-model="editRoleForm.showOrder" controls-position="right" :min="0" :max="10">
					</el-input-number>
				</el-form-item>

				<el-form-item label="状态" label-width="80px">
					<el-radio-group v-model="editRoleForm.roleState">
						<el-radio :key="item.dicDataId" :label="item.dicDataVal" v-for="item in dicRoleStateData">
							{{item.dicDataLabel}}
						</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="菜单权限" label-width="80px">

					<div class="el-tree tree-border">
						<el-tree :data="treeData" show-checkbox node-key="id" ref="mytree"
							:default-checked-keys="checkedKeys" highlight-current :props="defaultProps">
						</el-tree>
					</div>
				</el-form-item>


				<el-form-item label="备注" label-width="80px">
					<el-input type="textarea" :autosize="{ minRows: 3, maxRows: 10}" placeholder="请输入内容"
						v-model="editRoleForm.remark">
					</el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelForm()">取 消</el-button>
				<el-button type="primary" @click="editRole()">确 定</el-button>
			</span>
		</el-dialog>

		<el-table ref="multipleTable" :data="roleTableData" tooltip-effect="dark"
			style="width: 95%; margin-left: 20px;margin-top: 20px; " @selection-change="handleSelectionChange">
			<el-table-column type="selection">
			</el-table-column>

			<el-table-column prop="roleId" label="角色编号 " align="center">
			</el-table-column>
			<el-table-column prop="roleName" label="角色名称" align="center">
			</el-table-column>
			<el-table-column prop="roleChar" label="权限字符" align="center">
			</el-table-column>
			<el-table-column prop="showOrder" label="显示顺序" align="center">
			</el-table-column>
			<el-table-column prop="roleState" label="角色状态" align="center">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.roleState == 1 ? false : true" active-color="#13ce66"
						@change='changeStatus(scope.$index, scope.row)' inactive-color="#ff4949">
					</el-switch>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" align="center">
			</el-table-column>
			<el-table-column label="操作" align="center">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

					<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>


	</div>
</template>
<script>
	export default {
		data() {
			return {
				// 修改框显示状态
				editFormVisible: false,
				treeData: [],
				checkedKeys: [],
				val: '',
				defaultProps: {
					children: 'children',
					label: 'title'
				},

				addRoleForm: {
					roleName: '',
					roleChar: '',
					showOrder: '',
					roleState: '',
					authStr: ''
				},
				editRoleForm: {
					roleName: '',
					roleChar: '',
					showOrder: '',
					roleState: '',
					authStr: ''
				},
				// 新增角色弹出框的可见性
				addFormVisible: false,
				// 符合提交的角色数据数组
				roleTableData: [],
				// table选中的所有数据
				multipleSelection: [],
				// 修改 删除按钮，默认不可用
				editButtonState: true,
				delsButtonState: true,
				// 字典类型状态的可选数组
				dicRoleStateData: [],
				// 时间选择器选中时间的数组
				value1: [],
				// 查询框表单
				queryForm: {
					roleChar: '',
					roleName: '',
					roleState: '',
					startTime: '',
					endTime: ''
				},
			}
		},
		methods: {
			// 删除按钮多删除
			delRoleButtonClick() {
				let arr = [];
				let data = this.multipleSelection;
				for (let i = 0; i < data.length; i++) {
					arr[i] = data[i].roleId;
				}
				this.$confirm('此操作将永久删除选中的角色数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`roles/${arr}`)
						.then(resp => {
							if (resp.code == 20000) {
								this.$message({
									type: 'success',
									message: '删除成功!'
								});
							} else {
								this.$message({
									type: 'error',
									message: '删除失败!'
								});
							}
							this.getRoles(this.queryForm);
						});

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			getallmenu() {
				return this.$axios.get(`menu/getallmenu`)
			},
			handleEdit(index, row) {
				this.checkedKeys = [];

				if (this.treeData.length == 0) {
					this.getallmenu().then(resp => {
						this.treeData = resp.data;
						this.getCheckMenus(row);
					});
				} else {
					this.getCheckMenus(row);
				}

				this.editRoleForm = row;
				this.editFormVisible = true;
			},
			handleDelete(index, row) {
				this.$confirm('此操作将永久删除选中的角色数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`roles/${row.roleId}`)
						.then(resp => {
							if (resp.code == 20000) {
								this.$message({
									type: 'success',
									message: '删除成功!'
								});
							} else {
								this.$message({
									type: 'error',
									message: '删除失败!'
								});
							}
							this.getRoles(this.queryForm);
						});

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			getCheckMenus(row) {
				this.$axios.get(`roles/${row.roleId}`).then(resp => {
					if (resp.code == 20000) {
						// debugger;
						this.$refs.mytree.setCheckedKeys(resp.data)
						this.checkedKeys = resp.data;
					}
				});
			},
			// 修改框确定提交按钮
			editRole() {
				this.editFormVisible = false;
				let auth = this.$refs.mytree.getCheckedKeys().join(',') + ',' + this.$refs.mytree.getHalfCheckedKeys()
					.join(',');
				this.editRoleForm.authStr = auth;
				axios.put('/roles', this.editRoleForm).then(resp => {
					// console.log(resp);
					if (resp.code == 20000) {
						this.$message({
							type: 'success',
							message: '修改成功!',
						});
					} else {
						this.$message({
							type: 'error',
							message: '修改失败!',
						});
					}
					this.getRoles(this.queryForm);
				})
			},
			cancelForm() {
				this.addFormVisible = false;
				this.editFormVisible = false;
				this.getRoles(this.queryForm);
			},
			handleSelectionChange(val) {


				this.multipleSelection = val;
				console.log(val);
				if (val.length == 1) {
					this.$axios.get(`roles/${val[0].roleId}`).then(resp => {
						// console.log(resp);
						if (resp.code == 20000) {
							this.checkedKeys = resp.data;
							console.log(this.checkedKeys);
						}
					})
					this.editButtonState = false;
					this.delsButtonState = false;
				} else if (val.length > 1) {
					this.delsButtonState = false;
					this.editButtonState = true;
				} else {
					this.editButtonState = true;
					this.delsButtonState = true;
				}

			},
			// 点击修改按钮触发的事件
			editRoleButtonClick() {
				this.editFormVisible = true;
				this.$axios.get(`menu/getallmenu`).then(resp => {
					console.log(resp);
					this.treeData = resp.data;

				})
				let row = this.multipleSelection[0];
				this.editRoleForm = row;
				// this.checkedKeys = [];
				// 调用后端接口，查询菜单叶子节点id，传递回来一个数组/字符串，把角色id传到后端
				this.$axios.get(`roles/${row.roleId}`).then(resp => {
					// console.log(resp); 
					if (resp.code == 20000) {
						this.checkedKeys = resp.data;
						console.log(this.checkedKeys);
					}
				})
			},
			addRole() {
				let auth = this.$refs.mytree.getCheckedKeys().join(',') + ',' + this.$refs.mytree.getHalfCheckedKeys()
					.join(',');
				this.addRoleForm.authStr = auth;
				this.$axios.post('/roles', this.addRoleForm).then(resp => {
					// console.log(resp);
					this.addFormVisible = false;
					if (resp.code == 20000) {
						this.$message({
							type: 'success',
							message: '新增成功!',
						});
					} else {
						this.$message({
							type: 'error',
							message: '新增失败!',
						});
					}
					this.getRoles(this.queryForm);
				})
			},

			addRoleButtonClick() {
				this.addFormVisible = true;
				this.$axios.get(`menu/getallmenu`).then(resp => {
					console.log(resp);
					this.treeData = resp.data;

				})
			},
			changeStatus(index, row) {

				// console.log(this.dicData);

				this.dicRoleStateData.forEach(data => {

					if (data.dicDataVal == row.roleState) {
						let temp;
						this.$confirm(`此角色当前状态为${data.remark}, 是否修改角色状态?`, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.dicRoleStateData.forEach(data => {
								if (data.dicDataVal != row.roleState) {
									temp = data.dicDataVal;
								}
							})
							row.roleState = temp;
							axios.put('/roles', row).then(resp => {
								if (resp.code == 20000) {
									this.$message({
										type: 'success',
										message: '操作成功!',
									});
								} else if (resp.code == 50000) {
									this.$message({
										type: 'error',
										message: '操作失败!',
									});
								}
							})
							// this.$message({
							//   type: 'success',
							//   message: '操作成功!',
							// });
						}).catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
					}
				});
			},
			setQueryIni() {
				this.queryForm = {
					roleChar: '',
					roleName: '',
					roleState: '',
					startTime: '',
					endTime: ''
				}
			},

			// 重置查询框
			resetQueryForm() {
				this.value1 = [];
				this.setQueryIni();
				this.getRoles(this.queryForm);
			},
			// 点击搜索框触发的事件
			searchTableData() {
				if (this.value1 != null && this.value1 != undefined) {
					this.queryForm.startTime = this.value1[0];
					this.queryForm.endTime = this.value1[1];
				}
				// console.log(this.queryForm);
				this.getRoles(this.queryForm);
			},
			getRoles(searchData) {
				this.$axios.get("/roles", {
						params: searchData
					})
					.then(resp => {
						// console.log(resp);
						if (resp.code == 20000) {
							this.roleTableData = resp.data;
						}
					})
			}

		},
		mounted() {
			this.getRoles(this.queryForm);
		},
		created() {
			this.$axios.get("/users/dic/sys_role_hide").then(resp => {
				this.dicRoleStateData = resp.data;
			})
		}
	}
</script>

<style>
	.tree-border {
		margin-top: 5px;
		border: 1px solid #e5e6e7;
		background: #fff none;
		border-radius: 4px;
	}

	.el-tree {
		position: relative;
		cursor: default;
		background: #fff;
		color: #606266;
	}
</style>
